package com.ruoyi.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.teaching.domain.PlatformEEvent;
import com.ruoyi.teaching.domain.PlatformEEventApply;
import com.ruoyi.teaching.domain.UniversalCreateUpdate;
import com.ruoyi.teaching.domain.vo.PlatformEEventApplyVO;
import com.ruoyi.teaching.mapper.PlatformEEventApplyMapper;
import com.ruoyi.teaching.mapper.PlatformEEventMapper;
import com.ruoyi.teaching.service.PlatformEEventApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2025-03-04
 */
@Service
public class PlatformEEventApplyServiceImpl extends ServiceImpl<PlatformEEventApplyMapper, PlatformEEventApply> implements PlatformEEventApplyService {
    @Autowired
    private PlatformEEventApplyMapper platformEEventApplyMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private PlatformEEventMapper eventMapper;

    @Override
    public AjaxResult addApply(PlatformEEventApplyVO platformEEventApplyVO) {
        //报名前的校验
        QueryWrapper<PlatformEEventApply> platformEEventApplyQueryWrapper = new QueryWrapper<>();
        Long eventId = platformEEventApplyVO.getEventId();
        platformEEventApplyQueryWrapper.eq("event_id", eventId);
        platformEEventApplyQueryWrapper.eq("phone_num", platformEEventApplyVO.getPhoneNum());
        List<PlatformEEventApply> list = platformEEventApplyMapper.selectList(platformEEventApplyQueryWrapper);
        if (!list.isEmpty()) {
            return AjaxResult.error("该用户已报名，请勿重复提交报名信息。");
        }
        PlatformEEvent platformEEvent = eventMapper.selectById(eventId);
        if (null == platformEEvent) {
            return AjaxResult.error("赛事不存在");
        }
        String applyStartTime = platformEEvent.getApplyStartTime();
        String applyEndTime = platformEEvent.getApplyEndTime();

        // 获取北京时间
        LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));

        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            LocalDateTime startTime = applyStartTime != null ? LocalDateTime.parse(applyStartTime, formatter) : null;
            LocalDateTime endTime = applyEndTime != null ? LocalDateTime.parse(applyEndTime, formatter) : null;

            if (startTime != null && now.isBefore(startTime)) {
                return AjaxResult.error("报名暂未开始");
            } else if (endTime != null && now.isAfter(endTime)) {
                return AjaxResult.error("报名已截止");
            }

        } catch (DateTimeParseException e) {
            e.printStackTrace(); // 打印异常日志，方便排查
        }

        PlatformEEventApply platformEEventApply = new PlatformEEventApply();
        BeanUtils.copyProperties(platformEEventApplyVO, platformEEventApply);
        UniversalCreateUpdate createUpdate = UniversalUtil.getCreateUpdate(userMapper);
        platformEEventApply.setCreateBy(createUpdate.getName());
        platformEEventApply.setCreateId(createUpdate.getId());
        platformEEventApply.setCreateTime(DateUtils.getNowDate());
        int insert = platformEEventApplyMapper.insert(platformEEventApply);
        if (insert > 0) {
            return AjaxResult.success("申请成功");
        }
        return AjaxResult.error("申请失败");
    }

    @Override
    public AjaxResult listApplyByEventId(Integer pageNum, Integer pageSize, Long eventId, String name, String schoolName, Integer identityType) {
        if (null == eventId) {
            return new AjaxResult(HttpStatus.ERROR, "请选择赛事");
        }
        Page<PlatformEEventApply> platformEEventApplyPage = new Page<>(pageNum, pageSize);
        QueryWrapper<PlatformEEventApply> platformEEventApplyQueryWrapper = new QueryWrapper<>();
        platformEEventApplyQueryWrapper.eq("event_id", eventId);
        if (null != name && !name.equals("")) {
            platformEEventApplyQueryWrapper.like("name", name);
        }
        if (null != schoolName && !schoolName.equals("")) {
            platformEEventApplyQueryWrapper.like("school_name", schoolName);
        }
        if (null != identityType && identityType != 99) {
            platformEEventApplyQueryWrapper.eq("identity_type", identityType);
        }
        platformEEventApplyQueryWrapper.orderByDesc("create_time");
        Page<PlatformEEventApply> platformEEventApplyList = platformEEventApplyMapper.selectPage(platformEEventApplyPage,platformEEventApplyQueryWrapper);
        List<PlatformEEventApplyVO> platformEEventApplyVOList = new ArrayList<>();
        for (PlatformEEventApply platformEEventApply : platformEEventApplyList.getRecords()) {
            PlatformEEventApplyVO platformEEventApplyVO = new PlatformEEventApplyVO();
            BeanUtils.copyProperties(platformEEventApply, platformEEventApplyVO);
            if(StringUtils.isNotBlank(platformEEventApply.getAdviserTeacher())){
                String[] split = platformEEventApply.getAdviserTeacher().split(",");
                List<String> strings = new ArrayList<>(Arrays.asList(split));
                platformEEventApplyVO.setAdviserTeacher(strings);
            }
            platformEEventApplyVOList.add(platformEEventApplyVO);
        }
        Page<PlatformEEventApplyVO> platformEEventApplyPageVO = new Page<>(pageNum, pageSize);
        BeanUtils.copyProperties(platformEEventApplyPage, platformEEventApplyPageVO);
        platformEEventApplyPageVO.setRecords(platformEEventApplyVOList);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformEEventApplyPageVO);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deleteBatch(Long[] ids) {
        int i1 = platformEEventApplyMapper.deleteBatchIds(Arrays.asList(ids));
        if (i1 == ids.length) {
            return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
        }
        throw new RuntimeException("删除失败");
    }
}
